import Guide from '~/components/layout/guide'
import Snippet from '~/components/snippet'
import Caption from '~/components/text/caption'
import { Code, InlineCode } from '~/components/text/code'
import Note from '~/components/text/note'
import Request from '~/components/api/request'
import Link from '~/components/text/link'

export const meta = {
  title: 'Handling Node.js Request Bodies with ZEIT Now',
  description:
    'Parse Node.js request bodies for use inside Serverless Functions deployed with ZEIT Now.',
  published: '2019-05-10T09:03:14.819Z',
  authors: ['msweeneydev'],
  url: '/guides/handling-node-request-body',
  editUrl: 'pages/guides/handling-node-request-body.mdx',
  lastEdited: '2020-02-18T13:21:49.000Z'
}

In this guide, we will show you how to parse a [Node.js request body](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/), for use inside a [Serverless Function](/docs/v2/serverless-functions/introduction/) deployed to [ZEIT Now](/), without requiring a framework such as Express.

This guide assumes the request is sent with a [`Content-Type`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of [`application/json`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON). However, many more content types can be parsed if required.

## Step 1: Creating the Function

To get started, create a project directory with an `/api` directory inside and `cd` into it:

<Snippet dark text="mkdir req-body && mkdir req-body/api" />
<Caption>Creating an <InlineCode>/api</InlineCode> directory inside of a <InlineCode>/req-body</InlineCode> project.</Caption>

<Snippet dark text="cd req-body" />
<Caption>Moving into the <InlineCode>/req-body</InlineCode> project directory.</Caption>

To illustrate the parsing of a request body, create an `index.js` file inside your `/api` directory with the following code:

```js
module.exports = async (req, res) => {
  const { body } = req
  res.end(`Hello ${body.name}, you just parsed the request body!`)
}
```

<Caption>
  An example of how to parse a request body using{' '}
  <Link href="https://nodejs.org/dist/latest-v12.x/docs/api/">Node.js</Link>{' '}
  with a{' '}
  <Link href="/docs/runtimes#official-runtimes/node-js/node-js-request-and-response-objects/node-js-helpers">
    Helper property
  </Link>
  .
</Caption>

This function takes a POST request, parses the body, and uses data from the body in the response.

The key part here is line 2. [ZEIT Now](/) adds a number of Express like [helper properties](/docs/runtimes#official-runtimes/node-js/node-js-request-and-response-objects/node-js-helpers) to make wording with Node.js even easier.

<Note>
  You can read more about{' '}
  <Link href="/docs/runtimes#official-runtimes/node-js/node-js-request-and-response-objects/node-js-helpers">
    helper properties
  </Link>{' '}
  either in the <Link href="/blog/now-node-helpers">blog post</Link> or in the{' '}
  <Link href="/docs/runtimes#official-runtimes/node-js/node-js-request-and-response-objects/node-js-helpers">
    documentation
  </Link>
  .
</Note>

With the `req.body` helper, the incoming `request` is parsed automatically, removing the need for third-party libraries or further code to handle the [ReadableStream](https://nodejs.org/api/stream.html#stream_class_stream_readable) format the `request` normally arrives in.

## Step 2: Deploying the Function

Deploying your function to [ZEIT Now](/) can be done with **a single command**:

<Snippet dark text="now" />
<Caption>
  Deploying the app with the <InlineCode>now</InlineCode> command.
</Caption>

You have now created and deployed your project, all that's left to do is test that it works.

## Step 3: Sending the Request

To verify that the JSON is being parsed correctly, make a POST request to your new deployment using [curl](https://curl.haxx.se/) by executing the below code inside your terminal:

<Request
  method="POST"
  url="https://your-deployments-url.now.sh/api"
  headers={{
    'Content-Type': 'application/json'
  }}
  body={{
    name: 'Reader'
  }}
/>
<Caption>
    Making a POST request using <Link href="https://curl.haxx.se/">curl</Link>.
</Caption>

<Note>
  You should change the URL to match the one for your deployment given to you in
  the Now CLI.
</Note>

You will receive a response similar to the following:

<Code>Hello Reader, you just parsed the request body!</Code>
<Caption>
    An example response from making a POST request.
</Caption>

Congratulations, now you know how to parse request bodies with [ZEIT Now](/) in Node.js!

## Bonus: Understanding Why this Works

When [Node.js](https://nodejs.org/docs/latest-v8.x/api/) receives a request, the [body](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body) is in the format of a [ReadableStream](https://nodejs.org/api/stream.html#stream_class_stream_readable).

To get the data from the stream, you need to listen to its `data` and `end` events. To do this requires a few lines of code which you would much rather not have to repeat.

By using [helper properties](/docs/runtimes#official-runtimes/node-js/node-js-request-and-response-objects/node-js-helpers), the `request` is already parsed for you, allowing you to access the data immediately.

export default ({ children }) => <Guide meta={meta}>{children}</Guide>

export const config = {
  amp: 'hybrid'
}
